package com.tianluo.tianluobookstore.repository.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tianluo.tianluobookstore.BookPO;
import com.tianluo.tianluobookstore.BookPOExample;
import com.tianluo.tianluobookstore.mapper.BookPOMapper;
import com.tianluo.tianluobookstore.repository.BookRepository;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Repository
public class BookRepositoryImpl implements BookRepository {

    @Resource
    private BookPOMapper bookPOMapper;

    @Override
    public BookPO queryByIsbn(String isBn) {

        BookPOExample example = new BookPOExample();
        BookPOExample.Criteria criteria = example.createCriteria();
        criteria.andIsbnEqualTo(isBn);
        List<BookPO> bookPOList = bookPOMapper.selectByExample(example);

        if (!CollectionUtils.isEmpty(bookPOList)) {
            //唯一键，所以只有一个
            return bookPOList.get(0);
        }

        return null;
    }

    @Override
    public int updateBookStockByIdAndVersion(Integer bookId, Integer stockQuantity, Integer oldVersion) {

        BookPO bookPO = new BookPO();
        bookPO.setId(bookId);
        //每次更新，版本要都要加1，这个是乐观锁更新的必要前提
        bookPO.setVersion(oldVersion + 1);
        bookPO.setStockQuantity(stockQuantity);

        BookPOExample example = new BookPOExample();
        BookPOExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(bookId);
        criteria.andVersionEqualTo(oldVersion);
        return bookPOMapper.updateByExampleSelective(bookPO, example);
    }

    @Override
    public int insertBook(BookPO bookPO) {
        return bookPOMapper.insertSelective(bookPO);
    }

    @Override
    public PageInfo<BookPO> queryBookList(Integer pageNum, Integer pageSize) {
        // 设置分页参数
        PageHelper.startPage(pageNum, pageSize);

        // 构建查询条件
        BookPOExample example = new BookPOExample();
        example.setOrderByClause("created_time,id DESC"); // 按更新时间倒序排序

        // 执行查询
        List<BookPO> bookList = bookPOMapper.selectByExample(example);

        // 使用 PageInfo 包装分页结果
        return new PageInfo<>(bookList);
    }

    @Override
    public BookPO queryBookById(Integer bookId) {

        BookPOExample example = new BookPOExample();
        BookPOExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(bookId);

        List<BookPO> bookPOList = bookPOMapper.selectByExample(example);
        return !CollectionUtils.isEmpty(bookPOList) ? bookPOList.get(0) : null;
    }


}
